package com.jubaopen.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import com.jubaopen.bean.User;
import com.jubaopen.dao.UserDAO;
import com.jubaopen.util.PagedList;

public class UserService {

	@Autowired
	private UserDAO userDAO;

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public User queryById(int userId) {
		return userDAO.getOneById(userId);
	}

	public User queryByMobile(String mobile) {
		return userDAO.getOneByMobile(mobile);
	}

	public User queryFirmUserByMobile(String mobile) {
		return userDAO.getFirmByMobile(mobile);
	}
	
	public int addUser(User user) throws Exception {
		return userDAO.add(user);

	}

	public int updateUser(User user) throws Exception {
		return userDAO.update(user);
	}

	public User queryByPage(String page) {
		return userDAO.getGatherPage(page);
	}

	public PagedList<User> getUserList(Map<String, Object> queryMap,
			int pageIndex, int pageSize) {
		int skip = pageIndex * pageSize;
		List<User> userList = new ArrayList<User>();
		queryMap.put("skip", skip);
		queryMap.put("pageSize", pageSize);
		try {
			userList = userDAO.getPagedList(queryMap);
			PagedList<User> ret = new PagedList<User>();
			ret.setList(userList);
			if (pageIndex == 0) {
				int count = userDAO.getCount(queryMap);
				ret.setCount(count);
			}
			return ret;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public boolean save(User user){
		User entry = userDAO.getOneById(user.getId());
		int ret = 0;
		
		if(entry != null){
			user.setId(entry.getId());
			ret = userDAO.update(user);
		}else {
			ret = userDAO.add(user);
		}
		
		return ret>0 ? true:false; 
	}
}
